package com.base.utils;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.support.RequestContext;

public class LangUtils {
	/**
	 * 获取不同版本语言request
	 * @param request
	 * @param session
	 * @return
	 */
	public static RequestContext getLangRequestContext(HttpServletRequest request,
			HttpSession session){
		String lang = setLanguage(session);
		if(session.getAttribute("oldLan")!=null&&session.getAttribute("oldLan").equals(lang)){
			return new RequestContext(request);
		}
		session.setAttribute("oldLan",lang);
		if(lang.equals("zh")){
	        Locale locale = new Locale("zh", "CN"); 
	        session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale); 
	    } else if(lang.equals("en")){
	        Locale locale = new Locale("en", "US"); 
	        session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
	    } else {
	    	session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,LocaleContextHolder.getLocale());
	    }
		return new RequestContext(request);
	}
	
	/**
	 * 设置不同版本语言到session
	 * @param session
	 * @return
	 */
	public static String setLanguage(HttpSession session){
		String lang = (String) session.getAttribute("langType");
		if(lang==null||"".equals(lang))lang = "zh";
		session.setAttribute("langType", lang);
		return lang;
	}
}
